package cn.walls1717.wallsmall.ware.listener;

import cn.walls1717.wallsmall.common.pojo.to.OrderTO;
import cn.walls1717.wallsmall.common.pojo.to.mq.StockLockedTO;
import cn.walls1717.wallsmall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 库存解锁监听
 *
 * @author walls1717
 * @since 2022/11/22 22:53
 **/
@Service
@Slf4j
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Resource
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void unLockStockHandler(StockLockedTO stockLockedTO, Message message, Channel channel) throws IOException {
        try {
            log.info("收到解锁库存消息");
            wareSkuService.unLockStock(stockLockedTO);
            // 逐个确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 拒绝当前消息，并将当前消息重新放回消息队列。
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            e.printStackTrace();
        }

    }

    @RabbitHandler
    public void orderCloseHandler(OrderTO order, Message message, Channel channel) throws IOException {
        log.info("订单关闭，解锁库存");
        try {
            wareSkuService.unLockStock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
